<template>
  <div class="search-box">
    <!-- 顶部搜索区域 -->
    <form class="header-pos" action="/">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel"
        background="#3296fa" @focus="isShowResults=false" />
    </form>
    <!-- 搜索结果 -->
    <SearchResult :text='searchText' v-if='isShowResults'></SearchResult>
    <!-- 搜索历史 -->
    <SearchHistory @search="onSearch" :historyList='historyList' v-else-if='!searchText'></SearchHistory>
    <!-- 搜索建议 -->
    <SearchSuggestion @search="onSearch" :text='searchText' v-else></SearchSuggestion>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-results.vue'
import { setItem, getItem } from '@/utils/storage.js'
const TT_HOSTORY = 'tt_history'
export default {
  name: 'search',
  data () {
    return {
      // 搜索框内容
      searchText: '',
      // 显示搜索结果
      isShowResults: false,
      // 搜索历史
      historyList: getItem(TT_HOSTORY) || []
    }
  },
  methods: {
    // 搜索时触发
    onSearch (item) {
      // 搜索历史去重
      // 方法一
      // const index = this.historyList.findIndex(val => val === item)
      // if (index !== -1) {
      //   this.historyList.splice(index, 1)
      // }
      this.historyList.unshift(item)
      // 方法二
      this.historyList = [...new Set(this.historyList)]

      this.searchText = item
      this.isShowResults = true
    },
    // 取消时触发
    onCancel () {
      this.$router.go(-1)
    }
  },
  computed: {},
  watch: {
    // 监听搜索历史数组改变
    historyList (newVal) {
      setItem(TT_HOSTORY, newVal)
    }
  },
  filters: {},
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-box {
  .header-pos {
    position: sticky;
    top: 0;
    z-index: 2;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
